var is_robot_selected = true

var container = document.getElementById('robot-tag');

//添加机器人选择界面
function addRobotCard(id,src,caption) {
    const card = document.createElement('div');
    card.id = id;
    card.classList.add('App-blockly-robot-card');
    const img = document.createElement('img');
    img.src = src;
    const captionElement = document.createElement('p');
    captionElement.textContent = caption;
    card.appendChild(img);
    card.appendChild(captionElement);
    container.appendChild(card);
    card.onclick = function () {
        selected_robot = id   
    }
}


//添加键盘控制
let keyCheckbox = document.getElementById('key-control');
let key_control = document.getElementById('robot-key-control');
keyCheckbox.checked = false;
keyCheckbox.addEventListener('change', function(event) {
    if (event.target.type === 'checkbox') {
        if (event.target.checked) {
            rei_ros.add_keyboardToHtml({
                ros:ros,
                is_open:true,
            });
        } else {
            rei_ros.add_keyboardToHtml({
                ros:ros,
                is_open:false,
            });
        }
    }
});

const input = document.getElementById('rosip');
let rosip = input.value
const savedrosip = localStorage.getItem('rosip');
if (savedrosip) {
    input.value = savedrosip
    rosip = savedrosip
}

input.addEventListener('keydown', function (event) {
    if (event.key === 'Enter') {
        rosip = input.value
        localStorage.setItem('rosip', rosip);
        ros = rei_ros.linkMaster(rosip,'robot-state-lamp')
        reinovo = io.connect('http://'+rosip+':5000');
        initlink()
    }
});

let ros = rei_ros.linkMaster(rosip,'robot-state-lamp')
let reinovo = io.connect('http://'+rosip+':5000');
let Nav = new NavPose({
    ros:ros
})
let robotData = {}
let robotHistory = {}
let mapList = []
let PoseList = {}
let blocklyList = []
var Code = ''
let scan_topic = '/fuse_scan'

function initlink(){
    reinovo.on('RobotData_response', function (data) {
        is_sim = data.is_sim
        if (is_sim){
            scan_topic = 'scan'
        }
        robotHistory['log'] = data.log
        robotHistory['code'] = data.code 
        // console.log(robotHistory['code']);
        robotData = data
        mapList = robotData.maps_list
        var Poselen = Object.keys(PoseList).length
        PoseList = robotData.pose_list
        if(Poselen!=Object.keys(PoseList).length){
            updata_Goallist()
        }
        const log_window = document.getElementById('log-output')
        var log_output = log_window.querySelector('.rei-window-output')
        log_output.textContent = ''
        robotHistory.log.forEach(line => {
            const textNode = document.createTextNode(line);
            log_output.appendChild(textNode);
            const brNode = document.createElement('br')
            log_output.appendChild(brNode)
        })
        reinovo.emit('RobotData',{})
    });
    
    reinovo.emit('RobotData',{})
}
initlink()

var selectpose = document.getElementById('Goallist')

function updata_Goallist(){
    console.log('导航点更新')
    selectpose.innerHTML = ""
    blocklyList = []
    selectpose.appendChild(new Option('请选择导航点','-提示'))
    blocklyList.push(['选择导航点','选择导航点'])
    Object.keys(PoseList).forEach(key=>{
        blocklyList.push([key,key])
        var newoption = new Option(key,key)
        selectpose.appendChild(newoption)
    })
}

selectpose.onchange = function () {
    var navgoal_button = document.getElementById('nav-goal')
    var delgoal_button = document.getElementById('del-goal')
    var index=this.selectedIndex;
    if(index!=0){
        var name = this.options[index].value
        var pose = PoseList[name];
        var PosePub = new ROSLIB.Topic({
            ros : ros,
            name : 'now_pose',
            messageType : 'geometry_msgs/PoseStamped'
        })
        var pose = new ROSLIB.Message({
            header:{
                seq : 0,
                stamp : {
                    secs : 0,
                    nsecs : 0
                },
                frame_id:"map",
            },
            pose : {
                position : {
                    x : pose.position.x,
                    y : pose.position.y,
                    z : pose.position.z,
                },
                orientation : {
                    x : pose.orientation.x,
                    y : pose.orientation.y,
                    z : pose.orientation.z,
                    w : pose.orientation.w
                }
            }
        });
        PosePub.publish(pose);
        navgoal_button.addEventListener('click', function() {
            var goalPub = new ROSLIB.Topic({
                ros : ros,
                name : '/move_base_simple/goal',
                messageType : 'geometry_msgs/PoseStamped'
            })
            goalPub.publish(pose)
            rei_log('导航到目标点')
        })
        delgoal_button.addEventListener('click',function(){
            var result = window.confirm("你确定要删除导航点："+name+"吗？");
            if (result) {
                rei_log('删除导航点'+name)
                reinovo.emit('RobotData',{'delGoal':name})
            } else {
                console.log("用户点击了取消");
            }
        })
    }
}

function rei_log(msg) {
    console.log(msg);
    time = String(new Date())
    var list = time.split(' ')
    reinovo.emit('RobotData',{'log' :list[0]+' '+list[1]+' '+list[2]+' '+list[4]+' '+list[3]+'[INFO]' + msg})
};

reinovo.on('reinovo_response', function (log) {
    var data = log.time+"["+log.level+"]"+log.msg;
    console.log(data);
    reinovo.emit('RobotData',{'log' :data})
    reinovo.emit('reinovo_log','test');
});

var rviz = new rei_viewer({
    ros:ros,
    scan_topic:scan_topic,
    divID:'viewer_rviz'
})

window.onresize = function() {
    rviz.resize()
};

window.onbeforeunload = function() {
    console.log('-----------------页面刷新-----------------')
    var code = Blockly.JavaScript.workspaceToCode(workspace);
    reinovo.emit('RobotData',{'code':code})
    return '您确定要刷新页面吗？当前的操作可能会丢失。';
}

var testbutton = document.getElementById('App-blockly-toolbox')

testbutton.onclick = function(){
    if ('localStorage' in window) {
        var state = Blockly.serialization.workspaces.save(Blockly.getMainWorkspace());
        state = JSON.stringify(state)
        reinovo.emit('RobotData',{'code':state})
    }
}

// 初始化界面
function blocklyCodeInit () {
    rviz.stop()
    
    setTimeout(function () {
        // console.log(robotHistory['code'][0])
        try {
            var state = JSON.parse(robotHistory['code'][0])
            Blockly.serialization.workspaces.load(state, workspace);
        } catch (error) {
            console.log('代码区为空:');
        }

    },2000)
    window.addEventListener('unload',function(){
        if ('localStorage' in window) {
            var state = Blockly.serialization.workspaces.save(Blockly.getMainWorkspace());
            state = JSON.stringify(state)
            reinovo.emit('RobotData',{'code':state})
        }
    });
    setTimeout(function () {
        rviz = new rei_viewer({
            ros:ros,
            scan_topic:scan_topic,
            divID:'viewer_rviz'
        })
        rei_ros.add_joyToHtml({
            divID : 'bobac3-joy-left',
            axis : 'left',
            ros : ros,
        });
        rei_ros.add_joyToHtml({
            divID : 'bobac3-joy-reight',
            axis : 'reight',
            ros : ros,
        });
    }, 2000);
    reinovo.emit('reinovo_log','test');
    BlocklyStorage.backupOnUnload();
}

blocklyCodeInit()
var inter = 0

addDropDown('lauguage-button',{
    'zhan':'简体中文',
    'en':'English',
})

addDropDown('robot-tool',{
    'run-nav-node':'启动导航',
    'stop-nav-node':'关闭导航',
})

const openNav_button = document.getElementById('run-nav-node');

openNav_button.onclick = function () {
    if(ros_is_linked==true){
        alert('导航已打开')
    }else{
        new showPopup('open-nav');
    }
}

const openLogOutput = document.getElementById('App-blockly-log')

openLogOutput.onclick = function () {
    new showPopup('log-output')
}

const save_Goal = document.getElementById('save-goal')
var pose = {}

save_Goal.onclick = function () {
    if (ros_is_linked){
        var tfClient = new ROSLIB.TFClient({
            ros: ros,
            fixedFrame: 'map', // 设置固定参考系，通常为'world'，也需根据实际情况改变
            angularThres: 0.01, // 角度阈值，用于决定何时更新TF信息
            transThres: 0.01 // 平移阈值，用于决定何时更新TF信息
        });
        tfClient.subscribe('base_footprint', function (data) {
            pose = {
                position: {
                    x: data.translation.x,
                    y: data.translation.y,
                    z: data.translation.z
                },
                orientation: {
                    x: data.rotation.x,
                    y: data.rotation.y,
                    z: data.rotation.z,
                    w: data.rotation.w
                }
            }
        })
        new showPopup('save-goal-cfg')
    }else{
        alert('ros未连接')
    }
}

function saveGoal() {
    const Goalwindow = document.getElementById('save-goal-cfg')
    const re = /^[a-zA-Z0-9\u4e00-\u9fa5]+$/;
    if (Object.keys(pose).length === 0) {
        alert('订阅tf失败')
    }else{
        var goalname = document.getElementById('goal-name').value
        if (re.test(goalname)) {
            reinovo.emit('RobotData',{'goal':[goalname,pose]})
            pose = {}
            Goalwindow.style.visibility = 'hidden';
            alert('导航点保存成功')
            rei_log('导航点：'+goalname+'保存成功')
        }else{
            alert('导航点格式错误')
        }
    }
}

//增加鼠标悬浮下拉菜单
addDropDown('file-manager',{
    'load-blockly':'加载文件',
    'save-blockly':'保存文件',
})

addDropDown('App-blockly-toolbox',{
    'edit-point':'编辑导航点库',
    'save-point':'保存为导航点'
})

// 添加鼠标悬浮提示
addTips('App-blockly-log','日志')
addTips('robot-run','运行')
addTips('robot-stop','停止')
addTips('robot-data-visual','可视化工具')

//增加启动导航功能事件
const ros_start_nav = document.getElementById('ros_start_nav')

ros_start_nav.onclick = function () {
    // const getrosip = document.getElementById('rosip').value
    const open_nav_window = document.getElementById('open-nav')
    const get_navmap = document.getElementById('maplist').value
    $.ajax({
        url: "/startNav",
        type: "POST",
        data: {
            'cmd':'open',
            map_name:get_navmap
        },
        success: function(response){
            console.log(response.mssage)
            blocklyCodeInit()
            try{
                ros = rei_ros.linkMaster(rosip,'robot-state-lamp')
            } catch (e) {
                // this.style.cursor = 'default';
                console.log(e)
            }
        },
        error: function (xhr, status, error) {
            console.log("出错啦: " + error);
        }
    });
    open_nav_window.style.visibility = 'hidden';
}

const ros_stop_nav = document.getElementById('stop-nav-node')

ros_stop_nav.onclick = function () {
    $.ajax({
        url: "/startNav",
        type: "POST",
        data: {
            'cmd':'close'
        },
        success: function(response){
            console.log(response.mssage)
            ros.close()
            blocklyCodeInit()
        },
        error: function (xhr, status, error) {
            console.log("出错啦: " + error);
        }
    });
}


/**
 * 功能测试按钮！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！
 */

// 获取 rviz_view 元素
const rviz_view = document.getElementById('ros-rviz-view');
// 获取全屏按钮
const fullscreenButton = document.getElementById('robot-data-visual');

$(".rviz-joy-left").fadeOut("slow")
$(".rviz-joy-reight").fadeOut("slow")

// 检查浏览器是否支持全屏 API
function openFullscreen() {
    rei_ros.add_joyToHtml({
        divID : 'rviz-joy-left',
        axis : 'left',
        ros : ros,
    });
    rei_ros.add_joyToHtml({
        divID : 'rviz-joy-reight',
        axis : 'reight',
        ros : ros,
    });
    $(".rviz-joy-left").show("slow");
    $(".rviz-joy-reight").show("slow");
    if (rviz_view.requestFullscreen) {
        rviz_view.requestFullscreen().catch((err) => {
            console.error(`进入全屏失败: ${err.message}`);
        });
    } else if (rviz_view.webkitRequestFullscreen) {
        // Safari 浏览器
        rviz_view.webkitRequestFullscreen().catch((err) => {
            console.error(`进入全屏失败: ${err.message}`);
        });
    } else if (rviz_view.msRequestFullscreen) {
        // IE 浏览器
        rviz_view.msRequestFullscreen().catch((err) => {
            console.error(`进入全屏失败: ${err.message}`);
        });
    }
}

// 退出全屏函数
function closeFullscreen() {
    if (document.exitFullscreen) {
        document.exitFullscreen();
    } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen();
    } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
    }

}

document.addEventListener('fullscreenchange', () => {
    if (!document.fullscreenElement) {
        $(".rviz-joy-left").fadeOut("slow");
        $(".rviz-joy-reight").fadeOut("slow");
    }
});

document.addEventListener('webkitfullscreenchange', () => {
    if (!document.webkitFullscreenElement) {
        $(".rviz-joy-left").fadeOut("slow");
        $(".rviz-joy-reight").fadeOut("slow");
    }
});

document.addEventListener('msfullscreenchange', () => {
    if (!document.msFullscreenElement) {
        $(".rviz-joy-left").fadeOut("slow");
        $(".rviz-joy-reight").fadeOut("slow");
    }
});

// 为按钮添加点击事件监听器
fullscreenButton.addEventListener('click', function () {
    if (document.fullscreenElement) {
        closeFullscreen();
    } else {
        openFullscreen();
    }
});